/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.DictCache;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.admin.dto.*;
import org.springblade.modules.admin.dto.feishu.ElevatorMaintainCostListDTO;
import org.springblade.modules.admin.dto.feishu.GalaxyElevatorTrackUpdateDTO;
import org.springblade.modules.admin.dto.platform.BuildingSearchDTO;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.entity.es.ElevatorDocument;
import org.springblade.modules.admin.enums.*;
import org.springblade.modules.admin.mapper.ElevatorMapper;
import org.springblade.modules.admin.mapper.es.ElevatorDocumentMapper;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.utils.GenerateElevatorNumService;
import org.springblade.modules.admin.vo.*;
import org.springblade.modules.admin.vo.contract.ContractElevatorVoV2;
import org.springblade.modules.admin.vo.elevator.ElevatorFloorVo;
import org.springblade.modules.admin.vo.elevator.ElevatorIntactSearchVo;
import org.springblade.modules.admin.vo.elevator.ElevatorIntactVo;
import org.springblade.modules.admin.vo.feishu.BuildingElevatorFeiShuVO;
import org.springblade.modules.admin.vo.feishu.ElevatorDataReportVO;
import org.springblade.modules.admin.vo.feishu.GalaxyElevatorNumVO;
import org.springblade.modules.admin.vo.feishu.GovernmentElevatorPoolVO;
import org.springblade.modules.admin.vo.openapi.SidaElevatorBasicVO;
import org.springblade.modules.admin.vo.parts.PartWordUrlVo;
import org.springblade.modules.admin.vo.platform.ElevatorVo;
import org.springblade.modules.admin.vo.platform.TenantVO;
import org.springblade.modules.admin.vo.rescue.RescuePhoneVo;
import org.springblade.modules.admin.vo.sugar.bi.BIScreenElevatorPlanPartsVO;
import org.springblade.modules.admin.vo.sugar.bi.BIScreenElevatorVO;
import org.springblade.modules.admin.vo.sugar.bi.BIScreenElevatorPlanVO;
import org.springblade.modules.admin.vo.sugar.estate.ElevatorInfoVo;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IDictService;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static org.springblade.modules.admin.service.BuildingService.PROJECT_TYPE_CODE;

/**
 * 电梯信息 服务实现类
 *
 * @author BladeX
 * @since 2021-05-11
 */
@Service
@Slf4j
public class ElevatorServiceImpl extends BaseServiceImpl<ElevatorMapper, Elevator> implements ElevatorService {

	@Autowired
	@Lazy
	private IElevatorDetailService elevatorDetailService;
	@Autowired
	private ElevatorPlanStatusService elevatorPlanStatusService;
	@Autowired
	private ElevatorDriveModeService elevatorDriveModeService;
	@Autowired
	@Lazy
	private ElevatorAuditService elevatorAuditService;
	@Autowired
	private ITenantService tenantService;
	@Autowired
	private IUserService userService;
	@Autowired
	private BuildingElevatorTemplateReleService betReleService;
	@Autowired
	private IDeptService deptService;
	@Autowired
	private IElevatorBrandService elevatorBrandService;
	@Autowired
	@Lazy
	private GenerateElevatorNumService gens;
	@Autowired
	private IElevatorFieldVService elevatorFieldVService;
	@Autowired
	private IDictService dictService;
	@Autowired
	private IElevatorExtService elevatorExtService;
	@Autowired
	private IMaintainPlanConfigService planConfigService;
	@Autowired
	private IElevatorMaintainStatusDayService elevatorMaintainStatusDayService;
	@Autowired
	private IMaintainDayCountService maintainDayCountService;
	@Autowired
	private IElevatorEffectedService elevatorEffectedService;
	@Autowired
	private IElevatorAttachmentService elevatorAttachmentService;
	@Autowired
	private IElevatorAttachmentHistoryService elevatorAttachmentHistoryService;
	@Autowired
	private IElevatorFloorStandTemplateService elevatorFloorStandTemplateService;
	@Autowired
	private ElevatorDocumentMapper elevatorDocumentMapper;

	@Autowired
	@Lazy
	private IBuildingFloorElevatorService buildingFloorElevatorService;

	@Autowired
	@Lazy
	private IMaintainPlanConfigService maintainPlanConfigService;

	@Autowired
	@Lazy
	private IElevatorContractService elevatorContractService;

	@Autowired
	private ITenantExtService tenantExtService;

	@Autowired
	@Lazy
	private IBuildingUserService buildingUserService;


	@Autowired
	@Lazy
	private IElevatorPartsStructureTemplateRelationService elevatorPartsStructureTemplateRelationService;
	@Autowired
	private ElevatorDeviceService elevatorDeviceService;


	@Value("${project.api.url.estate}")
	private String estateApiUrl;

	@Override
	public IPage<ElevatorVO> selectElevatorPage(IPage<ElevatorVO> page, Elevator elevator) {
		return page.setRecords(baseMapper.selectElevatorPage(page, elevator));
	}

	@Override
	public IPage<ElevatorVO> selectElevatorPage(IPage<ElevatorVO> page, List<Long> elevatorIds) {
		return page.setRecords(baseMapper.selectElevatorPageByIds(page, elevatorIds));
	}

	@Override
	public ElevatorVO selectElevator(Long id) {

		ElevatorVO elevatorVO = baseMapper.selectElevator(id);
		if (elevatorVO == null) {
			throw new ServiceException("电梯id有误");
		}
		String releIds = elevatorVO.getReleIds();
		if (ObjectUtil.isNotEmpty(releIds)) {
			List<BuildingElevatorTemplateRele> releList = betReleService.listByIds(Func.toLongList(releIds));
			elevatorVO.setReleList(releList);
		}
		ElevatorFieldV fieldV = elevatorFieldVService.getOne(Wrappers.<ElevatorFieldV>lambdaQuery().eq(ElevatorFieldV::getElevatorId, id));
		elevatorVO.setFieldV(fieldV);
		ElevatorExt elevatorExt = elevatorExtService.getOne(Wrappers.<ElevatorExt>lambdaQuery().eq(ElevatorExt::getElevatorId, id));
		if (elevatorExt.getElevatorUserId() != null) {
			BuildingUser buildingUser = buildingUserService.getById(elevatorExt.getElevatorUserId());
			if (buildingUser != null) {
				elevatorExt.setBuildingUserName(buildingUser.getName());
			}
		}
		elevatorVO.setElevatorExt(elevatorExt);
		//使用附件
		List<ElevatorAttachmentHistory> attachmentList = elevatorAttachmentHistoryService.list(Wrappers.<ElevatorAttachmentHistory>lambdaQuery().eq(ElevatorAttachmentHistory::getElevatorId, id).eq(ElevatorAttachmentHistory::getStatus, ElevatorAttachmentEnum.IMG.getStatus()).orderByDesc(ElevatorAttachmentHistory::getCreateTime).last("LIMIT 1"));
		//使用铭牌
		List<ElevatorAttachmentHistory> nameAttachmentList = elevatorAttachmentHistoryService.list(Wrappers.<ElevatorAttachmentHistory>lambdaQuery().eq(ElevatorAttachmentHistory::getElevatorId, id).eq(ElevatorAttachmentHistory::getStatus, ElevatorAttachmentEnum.NAME.getStatus()).orderByDesc(ElevatorAttachmentHistory::getCreateTime).last("LIMIT 1"));
		elevatorVO.setCertificateList(attachmentList);
		elevatorVO.setNameList(nameAttachmentList);
		Long updateUserId = elevatorVO.getUpdateUser();
		if (!Func.isNull(updateUserId)) {
			User updateUser = userService.getById(updateUserId);
			elevatorVO.setUpdateUserName(updateUser.getRealName());
		}
		//新增附件内容
		Elevator elevator = this.getById(id);
		ElevatorDetail elevatorDetail = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId, id));
		elevatorVO.setWbPhoneImg(elevator.getWbPhoneImg());
		elevatorVO.setWbExtUrl(elevator.getWbExtUrl());
		elevatorVO.setBxExtUrl(elevator.getBxExtUrl());
		elevatorVO.setFloorPlatforms(elevator.getFloorPlatforms());
		elevatorVO.setFloorDoors(elevator.getFloorDoors());
		elevatorVO.setFloorTier(elevator.getFloorTier());
		elevatorVO.setElevatorNumImg(elevatorDetail.getElevatorNumImg());
		if (elevator.getFloorElevatorId() != null) {
			BuildingFloorElevator floorElevator = buildingFloorElevatorService.getById(elevator.getFloorElevatorId());
			if (floorElevator != null) {
				elevatorVO.setFloorNums(Convert.toStr(floorElevator.getFloorNums(), ""));
			}
		}

		SimpleElevatorInfoVO infoVO = elevatorDeviceService.getSimpleElevatorInfoByElevatorId(elevatorVO.getId());
		elevatorVO.setDeviceId(infoVO.getDeviceId());


		ElevatorAudit elevatorAudit = elevatorAuditService.getOne(Wrappers.<ElevatorAudit>lambdaQuery().eq(ElevatorAudit::getElevatorId, id));
		elevatorVO.setElevatorAudits(elevatorAudit);

		return elevatorVO;
	}

	@Override
	public ElevatorVO selectElevByPrivateNum(String privateNum, Long elevatorId) {
		return baseMapper.selectElevByPrivateNum(privateNum, elevatorId);
	}

	@Override
	public ElevatorVO selectElevatorByAddress(String elevatorAddress, Long buildingId) {
		return baseMapper.selectElevatorByAddress(elevatorAddress, buildingId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long saveElevator(ElevatorSaveDto elevatorSaveDto) {
		Elevator elevator = new Elevator();
		elevator.setSourceTenantId(AuthUtil.getTenantId());
		Tenant tenant = tenantService.getByTenantId(AuthUtil.getTenantId());
		elevator.setSourceTenantName(tenant.getTenantName());
		elevator.setSourceType(tenant.getCompanyCategory());
		elevator.setSourceUserName(userService.getById(AuthUtil.getUserId()).getRealName());

		BeanUtils.copyProperties(elevatorSaveDto, elevator);
		// 检查是否有相同电梯编码
		checkPrivateNum(elevator.getPrivateNum(), null);
		// 检查电梯位置是否重复
		checkElevatorAddress(elevatorSaveDto);
		// 检查电梯出厂编码是否重复
		if (StringUtil.isNotBlank(elevatorSaveDto.getFactoryNumber())) {
			int count = elevatorDetailService.count(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getFactoryNumber, elevatorSaveDto.getFactoryNumber()));
			if (count > 0) {
				throw new ServiceException("出厂编号不可重复");
			}
		}
		ElevatorDetail elevatorDetail = new ElevatorDetail();
		BeanUtils.copyProperties(elevatorSaveDto, elevatorDetail);
		ElevatorAudit elevatorAudit = elevatorSaveDto.getElevatorAudits();
		if(elevatorAudit == null){
			elevatorAudit= new ElevatorAudit();
		}
		if (ObjectUtil.isNotEmpty(elevator.getPrivateNum())) {
			//获取电梯年检时间
//            String auditTime = elevatorAuditService.getElevatorAuditTimeByPrivateNum(elevator.getPrivateNum());
//            elevator.setElevatorAudit(auditTime);
//            elevatorAudit.setAuditTime(auditTime);
		} else {
			elevator.setPrivateNum(null);
			elevatorDetail.setElevatorUseType(elevatorSaveDto.getElevatorUseType());
			elevatorDetail.setMadeDate(elevatorSaveDto.getMadeDate());
		}

		// 新增或修改项目电梯关联结构模板层级
		String releIds = betReleService.saveRele(elevatorSaveDto.getTemplateId(), elevatorSaveDto.getReleList());
		elevator.setTemplateId(elevatorSaveDto.getTemplateId());
		elevator.setReleIds(releIds);

		// 电梯品牌
		ElevatorBrand elevatorBrand = elevatorBrandService.getById(elevatorSaveDto.getBrandId());
		if (ObjectUtil.isNotEmpty(elevatorBrand)) {
			elevator.setBrandName(elevatorBrand.getBrandName());
		}
		elevatorDetail.setElevatorNumImgDate(new Date());
		elevator.setWbExtUrlDate(new Date());
		elevator.setWbPhoneImgDate(new Date());

		//完整性校验
		elevatorIntact(elevatorSaveDto, elevator);
		this.save(elevator);
		elevatorAudit.setElevatorId(elevator.getId());
		elevatorAuditService.updateElevatorAudit(elevatorAudit);
		elevatorDetail.setElevatorId(elevator.getId());

		elevatorDetailService.save(elevatorDetail);
		ElevatorPlanStatus elevatorPlanStatus = new ElevatorPlanStatus();
		elevatorPlanStatus.setElevatorId(elevator.getId());
		elevatorPlanStatusService.save(elevatorPlanStatus);

		// 更新电梯设备技术参数值
		this.updateElevatorFieldV(elevator.getId(), elevatorSaveDto.getElevatorUseType(), elevatorSaveDto.getFieldV());
		// 更新电梯关联使用单位数据
		this.updateElevatorExt(elevator.getId(), elevatorSaveDto.getElevatorExt());

		// 插入小程序码
		String wxAppCodeUrl = this.generateWxAppCode(elevator.getId());
		if (Func.isNotBlank(wxAppCodeUrl)) {
			elevator.setWxAppCodeUrl(wxAppCodeUrl);
			this.updateById(elevator);
		}

		// 当是新增的情况
		if (Func.isNull(elevatorSaveDto.getElevatorId())) {
			// 生成电梯唯一识别码
			String elevatorNum = gens.generateElevatorNum(elevator.getId());
			elevatorDetail.setElevatorNum(elevatorNum);
		}

		//再执行更新
		elevatorDetailService.updateById(elevatorDetail);
		//记录使用证标志
		Long currentElevatorId = elevator.getId();
		List<ElevatorAttachmentHistory> certificateMarkList = elevatorSaveDto.getCertificateMarkList();
		certificateMarkList.forEach(o -> {
			o.setElevatorId(currentElevatorId);
			o.setStatus(ElevatorAttachmentEnum.IMG.getStatus());
		});
		elevatorAttachmentHistoryService.saveBatch(certificateMarkList);
		// 记录铭牌
		List<ElevatorAttachmentHistory> nameAttachmentList = elevatorSaveDto.getNameAttachmentList();
		nameAttachmentList.forEach(o -> {
			o.setElevatorId(currentElevatorId);
			o.setStatus(ElevatorAttachmentEnum.NAME.getStatus());
		});
		elevatorAttachmentHistoryService.saveBatch(nameAttachmentList);
		// 2023-10-26 无论是新增还是编辑，同步ES
		ElevatorDocument document = new ElevatorDocument();
		document.setId(elevator.getId());
		document.setName(elevatorDetail.getElevatorAddress());
		document.setNamePinyin(elevatorDetail.getElevatorAddress());
		document.setAlias(elevatorDetail.getElevatorAlias());
		document.setAliasPinyin(elevatorDetail.getElevatorAlias());
		document.setBuildingId(elevator.getBuildingId());
		document.setTenantId(tenant.getTenantId());
		elevatorDocumentMapper.insert(document);

		//2024-07-26 新增电梯维保安装,改装大修信息-新增历史记录
		if (elevatorSaveDto.getWbPhoneImg() != null && elevatorSaveDto.getWbPhoneImg().size() > 0) {
			for (PartWordUrlVo partWordUrlVo : elevatorSaveDto.getWbPhoneImg()) {
				ElevatorAttachmentHistory wbPhoneImgHistory = new ElevatorAttachmentHistory();
				wbPhoneImgHistory.setElevatorId(currentElevatorId);
				wbPhoneImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				wbPhoneImgHistory.setStatus(ElevatorAttachmentEnum.WB_PHONE_IMG.getStatus());
				elevatorAttachmentHistoryService.save(wbPhoneImgHistory);
			}
		}

		if (elevatorSaveDto.getBxExtUrl() != null && elevatorSaveDto.getBxExtUrl().size() > 0) {
			for (PartWordUrlVo partWordUrlVo : elevatorSaveDto.getBxExtUrl()) {
				elevator.setBxExtUrlDate(new Date());
				ElevatorAttachmentHistory wbPhoneImgHistory = new ElevatorAttachmentHistory();
				wbPhoneImgHistory.setElevatorId(currentElevatorId);
				wbPhoneImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				wbPhoneImgHistory.setStatus(ElevatorAttachmentEnum.BX_IMG.getStatus());
				elevatorAttachmentHistoryService.save(wbPhoneImgHistory);
			}
		}

		if (elevatorSaveDto.getWbExtUrl() != null && elevatorSaveDto.getWbExtUrl().size() > 0) {
			for (PartWordUrlVo partWordUrlVo : elevatorSaveDto.getWbExtUrl()) {
				ElevatorAttachmentHistory wbExtUrlImgHistory = new ElevatorAttachmentHistory();
				wbExtUrlImgHistory.setElevatorId(currentElevatorId);
				wbExtUrlImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				wbExtUrlImgHistory.setStatus(ElevatorAttachmentEnum.WB_EXT_IMG.getStatus());
				elevatorAttachmentHistoryService.save(wbExtUrlImgHistory);
			}
		}

		if (elevatorSaveDto.getElevatorNumImg() != null && elevatorSaveDto.getElevatorNumImg().size() > 0) {
			for (PartWordUrlVo partWordUrlVo : elevatorSaveDto.getElevatorNumImg()) {
				ElevatorAttachmentHistory elevatorNumImgHistory = new ElevatorAttachmentHistory();
				elevatorNumImgHistory.setElevatorId(currentElevatorId);
				elevatorNumImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				elevatorNumImgHistory.setStatus(ElevatorAttachmentEnum.ELEVATOR_NUM_IMG.getStatus());
				elevatorAttachmentHistoryService.save(elevatorNumImgHistory);
			}
		}

		return currentElevatorId;
	}

	/**
	 * @return
	 * @Author lsay
	 * @Description {
	 * 更新电梯关联使用单位数据
	 * }
	 * @Date 9:52 2023/8/14
	 * @Param
	 **/
	private void updateElevatorExt(Long elevatorId, ElevatorExt ext) {
		ElevatorExt elevatorExt = elevatorExtService.getOne(Wrappers.<ElevatorExt>lambdaQuery().eq(ElevatorExt::getElevatorId, elevatorId));
		if (ObjectUtil.isNotEmpty(elevatorExt)) {
			ext.setId(elevatorExt.getId());
		}
		if (ObjectUtil.isEmpty(ext)) {
			ext = new ElevatorExt();
		}
		ext.setElevatorId(elevatorId);
		elevatorExtService.saveOrUpdate(ext);
	}

	/**
	 * 更新电梯设备技术参数值
	 *
	 * @param elevatorId
	 * @param elevatorUseType
	 * @param fieldV
	 */
	private void updateElevatorFieldV(Long elevatorId, Long elevatorUseType, ElevatorFieldV fieldV) {
		ElevatorFieldV elevatorFieldV = elevatorFieldVService.getOne(Wrappers.<ElevatorFieldV>lambdaQuery().eq(ElevatorFieldV::getElevatorId, elevatorId));
		fieldV.setDriveModeId(elevatorUseType);
		fieldV.setElevatorId(elevatorId);
		if (ObjectUtil.isNotEmpty(elevatorFieldV)) {
			fieldV.setId(elevatorFieldV.getId());
		}
		elevatorFieldVService.saveOrUpdate(fieldV);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateElevator(Long id, ElevatorSaveDto elevatorSaveDto) {
		Elevator oldElevator = getById(id);
		if (Func.isEmpty(oldElevator)) {
			throw new ServiceException("电梯不存在");
		}
		Elevator elevator = new Elevator();
		elevator.setId(id);
		BeanUtils.copyProperties(elevatorSaveDto, elevator);
		elevatorIntact(elevatorSaveDto, elevator);

		// 检查电梯位置是否重复
		checkElevatorAddress(elevatorSaveDto);

		// 检查电梯出厂编码是否重复
		if (StringUtil.isNotBlank(elevatorSaveDto.getFactoryNumber())) {
			int count = elevatorDetailService.count(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getFactoryNumber, elevatorSaveDto.getFactoryNumber()).ne(ElevatorDetail::getElevatorId, id));
			if (count > 0) {
				throw new ServiceException("出厂编号不可重复");
			}
		}

		ElevatorDetail elevatorDetail = new ElevatorDetail();
		BeanUtils.copyProperties(elevatorSaveDto, elevatorDetail);
		ElevatorAudit elevatorAudit = new ElevatorAudit();
		elevatorAudit.setElevatorId(id);
		Long modeId = null;
		if (ObjectUtil.isNotEmpty(elevator.getPrivateNum())) {
			// 检查电梯编码
			checkPrivateNum(elevatorSaveDto.getPrivateNum(), elevator.getId());
			//获取电梯年检时间
//            String auditTime = elevatorAuditService.getElevatorAuditTimeByPrivateNum(elevator.getPrivateNum());
//            elevator.setElevatorAudit(auditTime);
//            elevatorAudit.setAuditTime(auditTime);

		} else {
			elevator.setPrivateNum(null);
			elevator.setIsComplete(false);
			elevatorDetail.setElevatorUseType(elevatorSaveDto.getElevatorUseType());
			elevatorDetail.setMadeDate(elevatorSaveDto.getMadeDate());
		}

		// 新增或修改项目电梯关联结构模板层级
		String releIds = betReleService.saveRele(elevatorSaveDto.getTemplateId(), elevatorSaveDto.getReleList());
		elevator.setTemplateId(elevatorSaveDto.getTemplateId());
		elevator.setReleIds(releIds);


		elevatorAuditService.updateElevatorAudit(elevatorAudit);

		//更新电梯设备技术参数值
		this.updateElevatorFieldV(elevator.getId(), elevatorDetail.getElevatorUseType(), elevatorSaveDto.getFieldV());
		// 更新电梯关联使用单位数据
		this.updateElevatorExt(elevator.getId(), elevatorSaveDto.getElevatorExt());

		if (!Func.isNull(elevatorSaveDto.getElevatorId())) {
			// 电梯唯一识别码头状态更改
			String elevatorNum = elevatorDetail.getElevatorNum();
			if (Func.isNull(elevatorNum) || ObjectUtil.isEmpty(elevatorNum)) {
				// 补充生成 电梯唯一识别码
				String newNum = gens.generateElevatorNum(elevator.getId());
				elevatorDetail.setElevatorNum(newNum);
			} else {
				// 电梯唯一识别码 第一个字段更改状态
				String newNum = elevatorSaveDto.getUseType() + elevatorNum.substring(1);
				elevatorDetail.setElevatorNum(newNum);
				log.info("修改的码:{}", elevatorDetail.getElevatorNum());
			}
		}


		Long currentElevatorId = elevator.getId();
		// 记录使用证标志
		if (elevatorSaveDto.getCertificateMarkList() != null && elevatorSaveDto.getCertificateMarkList().size() > 0) {
			List<ElevatorAttachmentHistory> historyList = elevatorAttachmentHistoryService.list(Wrappers.<ElevatorAttachmentHistory>lambdaQuery().eq(ElevatorAttachmentHistory::getElevatorId, id).eq(ElevatorAttachmentHistory::getStatus, ElevatorAttachmentEnum.IMG.getStatus()));
			List<String> urls = new ArrayList<>(100);
			for (ElevatorAttachmentHistory elevatorAttachmentHistory : historyList) {
				com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(Convert.toStr(elevatorAttachmentHistory.getAttachment(), "{}"));
				if (jsonObject.size() > 0) {
					urls.add(Convert.toStr(jsonObject.get("url")));
				}
			}
			List<ElevatorAttachmentHistory> saveList = new ArrayList<>(16);
			for (ElevatorAttachmentHistory elevatorAttachmentHistory : elevatorSaveDto.getCertificateMarkList()) {
				com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(Convert.toStr(elevatorAttachmentHistory.getAttachment(), "{}"));
				if (jsonObject.size() > 0) {
					if (!urls.contains(Convert.toStr(jsonObject.get("url")))) {
						ElevatorAttachmentHistory elevatorAttachmentHistory1 = new ElevatorAttachmentHistory();
						elevatorAttachmentHistory1.setStatus(ElevatorAttachmentEnum.IMG.getStatus());
						elevatorAttachmentHistory1.setAttachment(elevatorAttachmentHistory.getAttachment());
						elevatorAttachmentHistory1.setElevatorId(id);
						saveList.add(elevatorAttachmentHistory1);
					}
				}
			}
			elevatorAttachmentHistoryService.saveBatch(saveList);
		}

		// 记录铭牌并且校验重复
		if (elevatorSaveDto.getNameAttachmentList() != null && elevatorSaveDto.getNameAttachmentList().size() > 0) {
			List<ElevatorAttachmentHistory> historyList = elevatorAttachmentHistoryService.list(Wrappers.<ElevatorAttachmentHistory>lambdaQuery().eq(ElevatorAttachmentHistory::getElevatorId, id).eq(ElevatorAttachmentHistory::getStatus, ElevatorAttachmentEnum.NAME.getStatus()));
			List<String> urls = new ArrayList<>(100);
			for (ElevatorAttachmentHistory elevatorAttachmentHistory : historyList) {
				if (elevatorAttachmentHistory.getAttachment() == null || elevatorAttachmentHistory.getAttachment().equals("null")) {
					continue;
				}
				com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(Convert.toStr(elevatorAttachmentHistory.getAttachment(), "{}"));
				if (jsonObject.size() > 0) {
					urls.add(Convert.toStr(jsonObject.get("url")));
				}
			}
			List<ElevatorAttachmentHistory> saveList = new ArrayList<>(16);
			for (ElevatorAttachmentHistory elevatorAttachmentHistory : elevatorSaveDto.getNameAttachmentList()) {
				com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(Convert.toStr(elevatorAttachmentHistory.getAttachment(), "{}"));
				if (jsonObject.size() > 0) {
					if (!urls.contains(Convert.toStr(jsonObject.get("url")))) {
						ElevatorAttachmentHistory elevatorAttachmentHistory1 = new ElevatorAttachmentHistory();
						elevatorAttachmentHistory1.setStatus(ElevatorAttachmentEnum.NAME.getStatus());
						elevatorAttachmentHistory1.setAttachment(elevatorAttachmentHistory.getAttachment());
						elevatorAttachmentHistory1.setElevatorId(id);
						saveList.add(elevatorAttachmentHistory1);
					}
				}
			}
			elevatorAttachmentHistoryService.saveBatch(saveList);
		}


		// 2023-10-26 无论是新增还是编辑，同步ES
		ElevatorDocument document = new ElevatorDocument();
		document.setId(elevator.getId());
		document.setName(elevatorDetail.getElevatorAddress());
		document.setNamePinyin(elevatorDetail.getElevatorAddress());
		document.setAlias(elevatorDetail.getElevatorAlias());
		document.setAliasPinyin(elevatorDetail.getElevatorAlias());
		document.setBuildingId(elevator.getBuildingId());
		document.setTenantId(elevator.getTenantId());
		//elevatorDocumentMapper.insert(document);

		//2024-07-26 新增电梯维保安装,改装大修信息-新增历史记录
		Elevator elevator2 = this.getById(id);
		if (elevatorSaveDto.getWbPhoneImg() != null && elevatorSaveDto.getWbPhoneImg().size() > 0) {
			List<PartWordUrlVo> wordUrlVos = filterExis(elevator2.getWbPhoneImg(), elevatorSaveDto.getWbPhoneImg());
			for (PartWordUrlVo partWordUrlVo : wordUrlVos) {
				elevator.setWbPhoneImgDate(new Date());
				ElevatorAttachmentHistory wbPhoneImgHistory = new ElevatorAttachmentHistory();
				wbPhoneImgHistory.setElevatorId(currentElevatorId);
				wbPhoneImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				wbPhoneImgHistory.setStatus(ElevatorAttachmentEnum.WB_PHONE_IMG.getStatus());
				elevatorAttachmentHistoryService.save(wbPhoneImgHistory);
			}
		}

		if (elevatorSaveDto.getBxExtUrl() != null && elevatorSaveDto.getBxExtUrl().size() > 0) {
			List<PartWordUrlVo> wordUrlVos = filterExis(elevator2.getBxExtUrl(), elevatorSaveDto.getBxExtUrl());
			for (PartWordUrlVo partWordUrlVo : wordUrlVos) {
				elevator.setBxExtUrlDate(new Date());
				ElevatorAttachmentHistory wbPhoneImgHistory = new ElevatorAttachmentHistory();
				wbPhoneImgHistory.setElevatorId(currentElevatorId);
				wbPhoneImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				wbPhoneImgHistory.setStatus(ElevatorAttachmentEnum.BX_IMG.getStatus());
				elevatorAttachmentHistoryService.save(wbPhoneImgHistory);
			}
		}

		if (elevatorSaveDto.getWbExtUrl() != null && elevatorSaveDto.getWbExtUrl().size() > 0) {
			List<PartWordUrlVo> wordUrlVos = filterExis(elevator2.getWbExtUrl(), elevatorSaveDto.getWbExtUrl());
			for (PartWordUrlVo partWordUrlVo : wordUrlVos) {
				elevator.setWbExtUrlDate(new Date());
				ElevatorAttachmentHistory wbExtUrlImgHistory = new ElevatorAttachmentHistory();
				wbExtUrlImgHistory.setElevatorId(currentElevatorId);
				wbExtUrlImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				wbExtUrlImgHistory.setStatus(ElevatorAttachmentEnum.WB_EXT_IMG.getStatus());
				elevatorAttachmentHistoryService.save(wbExtUrlImgHistory);
			}
		}

		if (elevatorSaveDto.getElevatorNumImg() != null && elevatorSaveDto.getElevatorNumImg().size() > 0) {
			ElevatorDetail elevatorDetail3 = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId, id));
			List<PartWordUrlVo> wordUrlVos = filterExis(elevatorDetail3.getElevatorNumImg(), elevatorSaveDto.getElevatorNumImg());
			for (PartWordUrlVo partWordUrlVo : wordUrlVos) {
				elevatorDetail.setElevatorNumImgDate(new Date());
				ElevatorAttachmentHistory elevatorNumImgHistory = new ElevatorAttachmentHistory();
				elevatorNumImgHistory.setElevatorId(currentElevatorId);
				elevatorNumImgHistory.setAttachment(JSON.toJSONString(partWordUrlVo));
				elevatorNumImgHistory.setStatus(ElevatorAttachmentEnum.ELEVATOR_NUM_IMG.getStatus());
				elevatorAttachmentHistoryService.save(elevatorNumImgHistory);
			}
		}

		elevatorDetailService.update(elevatorDetail, new LambdaUpdateWrapper<ElevatorDetail>().eq(ElevatorDetail::getElevatorId, id));
		ElevatorDetail elevatorDetail2 = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId, id));
		if (modeId != null && elevatorIsComplete(elevatorDetail2)) {
			elevator.setIsComplete(true);
		} else {
			elevator.setIsComplete(false);
		}
		// 2025-08 新增 电梯sourceDesc字段
		elevator.setSourceDesc(elevatorSaveDto.getSourceDesc());
		elevator.setSourceStatus(elevatorSaveDto.getSourceStatus());
		elevator.setLifeStatus(elevatorSaveDto.getLifeStatus());
		this.updateById(elevator);

		// 同步层站结构
		if (!(floorPlatformsCompare(oldElevator.getFloorPlatforms(), elevator.getFloorPlatforms())
			&& floorDoorsCompare(oldElevator.getFloorDoors(), elevator.getFloorDoors()))) {
			elevatorFloorStandTemplateService.syncElevatorFloorStandTemplate(id, elevator.getFloorPlatforms(), elevator.getFloorDoors());
		}

		//电梯提醒
		if (elevatorSaveDto.getElevatorAudits() != null) {
			ElevatorAudit elevatorAudits = elevatorSaveDto.getElevatorAudits();
			elevatorAuditService.saveOrUpdate(elevatorAudits);
		}
		return true;
	}

	@Override
	public List<ElevatorDetail> getListByBuildingId(Long buildingId, List<Long> elevatorIds) {
		return baseMapper.getListByBuildingId(buildingId,elevatorIds);
	}

	/**
	 * 根据电梯设备代码获取电梯制造日期
	 *
	 * @param privateNum
	 */
	private Date getElevatorMadeDate(String privateNum) {
		Date madeDate = null;
		if (privateNum.length() == 20) {
			// 制造日期
			try {
				madeDate = DateUtil.parse(privateNum.substring(10, 16), "yyyyMM");
			} catch (Exception e) {
				return madeDate;
			}
		}
		return madeDate;
	}

	/**
	 * 根据设备代码前4位获取电梯驱动方式
	 *
	 * @param privateNum
	 * @return
	 */
	private Long getElevatorDriveModeByPrivateNum(String privateNum) {
		ElevatorDriveMode elevatorDriveMode = elevatorDriveModeService.getOne(Wrappers.<ElevatorDriveMode>lambdaQuery().eq(ElevatorDriveMode::getCode, privateNum.length() > 4 ? privateNum.substring(0, 4) : privateNum));
		if (ObjectUtil.isEmpty(elevatorDriveMode)) {
			return null;
		}
		return elevatorDriveMode.getId();
	}

	/**
	 * @Date 9:01 2021/3/25
	 * @Description {
	 * // 检查电梯编码是否重复
	 * }
	 * @Author lsay
	 **/
	private void checkPrivateNum(String privateNum, Long elevatorId) {
		if (ObjectUtil.isNotEmpty(privateNum)) {
			if (privateNum.length() < 4) {
				throw new ServiceException("设备编码格式异常");
			}
			ElevatorVO elevatorVO = this.selectElevByPrivateNum(privateNum, elevatorId);
			if (Func.notNull(elevatorVO)) {
				String address = elevatorVO.getBuildingName() + "-" + elevatorVO.getElevatorAddress();
				throw new ServiceException("与现有电梯（" + address + ")编码相同，请确认后再次输入");
			}
		}
	}

	/**
	 * @Date 9:01 2021/3/25
	 * @Description {
	 * // 检查电梯位置是否重复
	 * }
	 * @Author lsay
	 **/
	private void checkElevatorAddress(ElevatorSaveDto elevator) {
		ElevatorVO elevatorVO = this.selectElevatorByAddress(elevator.getElevatorAddress(), elevator.getBuildingId());
		if (elevatorVO != null && !elevatorVO.getId().equals(elevator.getId())) {
			String address = elevatorVO.getBuildingName() + "-" + elevatorVO.getElevatorAddress();
			throw new ServiceException("电梯位置与现有电梯（" + address + ")相同，请确认后再次输入");
		}
	}

	@Override
	public Boolean updateElevatorIsStop(Long elevatorId, Integer isStop) {
		Elevator elevator = this.getById(elevatorId);
		if (Func.isEmpty(elevator)) {
			return false;
		}
		elevator.setIsStop(isStop);
		return this.updateById(elevator);
	}

	@Override
	public IPage<ElevatorVo> elevatorListV2(IPage<ElevatorVo> page, BuildingSearchDTO buildingSearchDTO) {
		return baseMapper.elevatorListV2(page, buildingSearchDTO);
	}

	@Override
	public List<ElevatorSimpleInfoVO> elevatorSelectList(Long buildingId) {
		return baseMapper.elevatorSelectList(buildingId);
	}

	@Override
	public TlwElevatorDetailVO getTlwElevatorDetail(Long elevatorId) {
		return baseMapper.getTlwElevatorDetail(elevatorId);
	}

	@Override
	public List<ElevatorSimpleInfoVO> elevatorTlwSelectList(PlanConfigSearchVO search) {
		return baseMapper.elevatorTlwSelectList(search);
	}

	@Override
	public List<TenantVO> elevatorTenantList(BuildingSearchDTO buildingSearchDTO) {
		return baseMapper.elevatorTenantList(buildingSearchDTO);
	}

	@Override
	public IPage<ElevatorPageVO> devicePage(IPage<Object> page, ElevatorSearchVO search) {
		return baseMapper.devicePage(page, search);
	}

	@Override
	public IPage<TlwElevatorPageVO> tlwPage(PlanConfigSearchVO search, IPage<TlwElevatorPageVO> page) {
		return page.setRecords(baseMapper.tlwPage(page, search));
	}

	@Override
	public List<TlwElevatorPageVO> selectElevatorByDeviceId(String deviceId) {
		return baseMapper.selectListByDeviceId(deviceId);
	}

	@Override
	public List<WxAppCodeVO> batchDownloadWxAppCode(List<Long> elevatorIds) {
		return baseMapper.batchDownloadWxAppCode(elevatorIds);
	}

	@Override
	public String generateWxAppCode(Long elevatorId) {
		String url = "/estate/elevator/generateWxAppCode";
		Map<String, Object> paramMap = new HashMap<>(2);
		paramMap.put("elevatorId", elevatorId);
		HttpServletRequest request = WebUtil.getRequest();
		String token = AuthUtil.getHeader(request);
		paramMap.put(TokenConstant.HEADER, token);
		String result = null;
		try {
			result = HttpUtil.get(estateApiUrl + url, paramMap, 10000);
		} catch (IORuntimeException e) {
			throw new ServiceException("获取小程序码异常!");
		}

		JSONObject jsonObject = JSONUtil.parseObj(result);
		if (Func.toInt(jsonObject.get("code")) != 200) {
			throw new ServiceException("获取小程序码异常!");
		}

		return Func.toStr(jsonObject.get("data"), null);
	}

	@Override
	public IPage<ElevatorDossierVO> elevatorDossierPage(IPage<ElevatorDossierVO> page, ElevatorVO elevator) {
		List<ElevatorDossierVO> list = baseMapper.elevatorDossierPage(page, elevator);
		list.forEach(elevatorDossierVO -> {
			if (elevatorDossierVO.getContractSource() == null) {
				List<ElevatorContract> list1 = elevatorContractService.getList(elevatorDossierVO.getId());
				if (list1.size() > 0) {
					ElevatorContract elevatorContract = list1.get(list1.size() - 1);
					if (Convert.toInt(elevatorContract.getContractExtStatus(), -10) == 4) {
						elevatorDossierVO.setContractSource(4);
					} else if (Convert.toInt(elevatorContract.getContractStatus()) == 3) {
						elevatorDossierVO.setContractSource(10);
					}
				}
			}
			elevatorDossierVO.setTypeName(DictCache.getValue(PROJECT_TYPE_CODE, elevatorDossierVO.getType()));
		});
		return page.setRecords(list);
	}

	@Override
	public IPage<ElevatorDossierVO> elevatorDossierPageByEleNum(IPage<ElevatorDossierVO> page, String elevatorNum) {
		List<ElevatorDossierVO> list = baseMapper.elevatorDossierByelevatorNum(page, elevatorNum);
		list.forEach(elevatorDossierVO -> elevatorDossierVO.setTypeName(DictCache.getValue(PROJECT_TYPE_CODE, elevatorDossierVO.getType())));
		return page.setRecords(list);
	}

	@Override
	public ElevatorRelationDetailVO selectElevatorRelationDetail(Long elevatorId) {
		return baseMapper.selectElevatorRelationDetail(elevatorId);
	}

	@Override
	public Map<String, Object> elevatorDossierCount() {
		return baseMapper.elevatorDossierCount();
	}

	@Override
	public Boolean elevatorCheckAuditType(Long elevatorId, Integer useType) {
		ElevatorDetail elevatorDetail = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId, elevatorId));
		// 电梯年审类型为空允许修改
		if (ObjectUtil.isEmpty(elevatorDetail.getUseType())) {
			return Boolean.TRUE;
		}
		// 电梯年审类型与修改值相同允许修改
		if (elevatorDetail.getUseType().equals(useType)) {
			return Boolean.TRUE;
		}
		// 查询电梯最后一张工单
		MaintainPlanContent planContent = baseMapper.selectElevatorLastPlan(elevatorId);
		// 没有工单允许修改
		if (ObjectUtil.isEmpty(planContent)) {
			return Boolean.TRUE;
		}
		// 工单状态为维保签字或已完成允许修改
		if (planContent.getStatus().equals(TaskStatusEnum.BY_MAINTAIN_SIGN.getStatus()) || planContent.getStatus().equals(TaskStatusEnum.BY_SIGN.getStatus())) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	@Override
	public List<RobotElevatorSearchVO> getElevatorSearch(List<Long> buildingIds) {
		List<RobotElevatorSearchVO> voList = baseMapper.getElevatorByBuilding(buildingIds);
		return voList;
	}

	@Override
	public List<Dict> driverModeFieldSelect(String code, String driverModeCode, String driverModeKey) {
		List<Dict> dictList = new ArrayList<>();
		dictList = dictService.getList(code);
		if (ObjectUtil.isNotEmpty(driverModeCode)) {
			if (driverModeCode.equals("3110") || driverModeCode.equals("3120") || driverModeCode.equals("3130")) {
				dictList = dictService.getList("controlModeA");
			} else if (driverModeCode.equals("3220") || driverModeCode.equals("3210")) {
				dictList = dictService.getList("controlModeB");
			} else if (driverModeCode.equals("3410") || driverModeCode.equals("3420") || driverModeCode.equals("3430")) {
				if (ObjectUtil.isNotEmpty(driverModeKey)) {
					if (driverModeKey.equals("1") || driverModeKey.equals("2")) {
						dictList = dictService.getList("controlModeA");
					} else {
						dictList = dictService.getList("controlModeB");
					}
				}
			}
		}
		return dictList;
	}

	@Override
	public Object testDetailFieldV() {
		List<ElevatorDetail> elevatorDetailList = elevatorDetailService.list();
		List<ElevatorFieldV> elevatorFieldVS = new ArrayList<>();
		elevatorDetailList.forEach(e -> {
			ElevatorFieldV elevatorFieldV = new ElevatorFieldV();
			elevatorFieldV.setElevatorId(e.getElevatorId());
			elevatorFieldV.setTier(e.getFloorHigh());
			elevatorFieldV.setStand(e.getStand());
			elevatorFieldV.setDoor(e.getDoor());
			elevatorFieldV.setRatedSpeed(e.getSpeed());
			elevatorFieldV.setRatedWeight(e.getSupportingPower());
			elevatorFieldV.setDriveModeId(e.getElevatorUseType());
			elevatorFieldVS.add(elevatorFieldV);
		});
		return elevatorFieldVService.saveBatch(elevatorFieldVS);
	}

	@Override
	public List<ElevatorInfoVo> getList(Long buildingId, String tenantId) {
		return baseMapper.getList(buildingId, tenantId);
	}

	/**
	 * 异步处理年检时间
	 *
	 * @param elevatorList
	 */
	@Async
	@Override
	public void auditTimeTask(List<Elevator> elevatorList) {
		for (Elevator elevator : elevatorList) {
			//获取电梯年检时间
			String auditTime = elevatorAuditService.getElevatorAuditTimeByPrivateNum(elevator.getPrivateNum());
			if (Func.isBlank(auditTime)) {
				continue;
			}
			elevator.setElevatorAudit(auditTime);
			this.updateById(elevator);
			ElevatorAudit elevatorAudit = new ElevatorAudit();
			elevatorAudit.setAuditTime(auditTime);
			elevatorAudit.setElevatorId(elevator.getId());
			elevatorAuditService.updateElevatorAudit(elevatorAudit);
		}
	}

	@Override
	public IPage<ElevatorPrincipalPageVO> selectElevatorPrincipalPage(IPage<ElevatorPrincipalPageVO> page, ElevatorPrincipalQueryDTO queryDTO) {
		// 处理获取部门子集
		if (ObjectUtil.isNotEmpty(queryDTO.getDeptIds())) {
			List<Long> deptIdList = new ArrayList<>();
			queryDTO.getDeptIds().forEach(e -> {
				List<Dept> childIds = deptService.getDeptChild(e);
				if (ObjectUtil.isNotEmpty(childIds)) {
					deptIdList.addAll(childIds.stream().map(Dept::getId).collect(Collectors.toList()));
				}
			});
			deptIdList.addAll(queryDTO.getDeptIds());
			queryDTO.setDeptIds(deptIdList.stream().distinct().collect(Collectors.toList()));
		}
		// 设置维保负责人
		List<ElevatorPrincipalPageVO> pageVOS = baseMapper.selectElevatorPrincipalPage(page, queryDTO);
		Map<String, List<Dept>> map = new HashMap<>(10);
		List<String> deptIds = pageVOS.stream().filter(o -> o.getAncestors() != null).map(ElevatorPrincipalPageVO::getAncestors).distinct().collect(Collectors.toList());
		for (String deptId : deptIds) {
			List<Long> ancestorsIds = Func.toLongList(deptId);
			List<Dept> ancestorsDept = deptService.listByIdsOrderByIds(ancestorsIds);
			map.put(deptId, ancestorsDept);
		}
		if (ObjectUtil.isNotEmpty(pageVOS)) {
			pageVOS.forEach(e -> {
				if (e.getUseType().equals(ElevatorAuditTypeEnum.NOT_AUDIT.getStatus())) {
					e.setOverdueDateDesc("--");
				}
				if (e.getMaintainStatus().equals(ElevatorMaintainStatusEnums.RELEASE_INSURANCE.getId())) {
					e.setOverdueDateDesc("--");
				}
				if (ObjectUtil.isEmpty(e.getOverdueDate())) {
					e.setOverdueDateDesc("--");
				}
				if (ObjectUtil.isNotEmpty(e.getPrincipalUserIds())) {
					List<Long> userIds = Func.toLongList(",", e.getPrincipalUserIds());
					List<String> userNames = Func.toStrList(",", e.getPrincipalUserNames());
					List<User> userList = new ArrayList<>();
					for (int i = 0; i < userIds.size(); i++) {
						User user = new User();
						user.setId(userIds.get(i));
						user.setRealName(userNames.get(i));
						userList.add(user);
					}
					e.setUserList(userList);
				}
				if (ObjectUtil.isNotEmpty(e.getPrincipalDeptId()) && ObjectUtil.isNotEmpty(e.getAncestors())) {
					e.setAncestorsDept(map.get(e.getAncestors()));
				}
			});
		}
		return page.setRecords(pageVOS);
	}

	@Override
	public Map<String, Integer> selectElevatorPrincipalCount() {
		Map<String, Integer> map = baseMapper.selectElevatorPrincipalCount();
		MaintainPlanConfigVO maintainPlanConfig = new MaintainPlanConfigVO();
		maintainPlanConfig.setIsPlan(0);
		maintainPlanConfig.setNextPlanDateOrderBy("asc");
		maintainPlanConfig.setSearchMaintainStatus("2");
		Query query = new Query();
		IPage<MaintainPlanConfigVO> pages = maintainPlanConfigService.selectMaintainPlanConfigPage(Condition.getPage(query), maintainPlanConfig);
		Integer total = Convert.toInt(pages.getTotal());
		map.put("noPlan", total);
		return map;
	}

	@Override
	public Boolean checkPrincipalDeptUser(String deptId, String userIds) {
		AtomicReference<Boolean> result = new AtomicReference<>(Boolean.TRUE);
		List<User> userList = userService.listByIds(Func.toLongList(userIds));
		List<String> deptIds = userList.stream().map(User::getDeptId).collect(Collectors.toList());
		if (ObjectUtil.isNotEmpty(deptIds)) {
			deptIds.forEach(e -> {
				if (!e.contains(deptId)) {
					result.set(Boolean.FALSE);
				}
			});
		}
		return result.get();
	}

	@Override
	public void downExcelElevatorPrincipal(ElevatorPrincipalQueryDTO queryDTO, List<List<String>> rows) {
		// 处理获取部门子集
		if (ObjectUtil.isNotEmpty(queryDTO.getDeptIds())) {
			List<Long> deptIdList = new ArrayList<>();
			queryDTO.getDeptIds().forEach(e -> {
				List<Dept> childIds = deptService.getDeptChild(e);
				if (ObjectUtil.isNotEmpty(childIds)) {
					deptIdList.addAll(childIds.stream().map(Dept::getId).collect(Collectors.toList()));
				}
			});
			deptIdList.addAll(queryDTO.getDeptIds());
			queryDTO.setDeptIds(deptIdList);
		}
		// 设置维保负责人
		queryDTO.setType(1);
		List<ElevatorPrincipalPageVO> pageVOS = baseMapper.selectElevatorPrincipal(queryDTO);
		if (ObjectUtil.isNotEmpty(pageVOS)) {
			pageVOS.forEach(e -> {
				List<String> row = new ArrayList<>(11);
				row.add(Convert.toStr(e.getBuildingName()));
				row.add(Convert.toStr(e.getBuildingAddress()));
				row.add(Convert.toStr(e.getElevatorAddress()));
				row.add(Convert.toStr(ElevatorAuditTypeEnum.getName(e.getUseType())));
				row.add(Convert.toStr(e.getMaintainStatusDesc()));
				row.add(Convert.toStr(e.getEleMaintainStatusDesc(), "-"));
				if (e.getUseType().equals(ElevatorAuditTypeEnum.AUDIT.getStatus())) {
					if (ObjectUtil.isNotEmpty(e.getOverdueDate())) {
						Date now = DateUtil.parseDate(DateUtil.today());
						if (e.getOverdueDate().getTime() == now.getTime()) {
							row.add("明天即将违规");
							row.add("");
						} else if (e.getOverdueDate().getTime() > now.getTime()) {
							row.add("正常");
							row.add("");
						} else {
							long betweenDay = DateUtil.between(e.getOverdueDate(), now, DateUnit.DAY);
							row.add("已违规");
							row.add(Convert.toStr(betweenDay));
						}
					} else {
						row.add("");
						row.add("");
					}
				} else {
					row.add("");
					row.add("");
				}
				row.add(Convert.toStr(DateUtil.format(e.getPreviousPlanDate(), "yyyy-MM-dd")));
				row.add(Convert.toStr(DateUtil.format(e.getNextPlanDate(), "yyyy-MM-dd")));
				row.add(Convert.toStr(StringUtil.isNotBlank(e.getPrincipalDeptName()) ? e.getPrincipalDeptName() : "未分配"));
				row.add(Convert.toStr(StringUtil.isNotBlank(e.getPrincipalUserNames()) ? e.getPrincipalUserNames() : "未分配"));
				row.add(Convert.toStr(DateUtil.format(e.getUpdateTime(), "yyyy-MM-dd HH:mm:ss")));
				Integer toInt = Convert.toInt(e.getFromType(), 0);
				if (toInt == 1) {
					row.add("外包合同");
				} else if (toInt == 2) {
					row.add("非外包合同");
				} else {
					row.add("/");
				}
				row.add(Convert.toStr(e.getElevatorNum()));
				rows.add(row);
			});
		}
	}

	@Override
	public ElevatorPageVO findElevatorPageVOByElevatorId(Long elevatorId) {
		return this.baseMapper.selectByElevatorId(elevatorId);
	}

	@Override
	public Boolean elevatorIsComplete(ElevatorDetail elevatorDetail) {

		if (StrUtil.isEmpty(elevatorDetail.getSecurityGuardName())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getSupportingPower())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getRegisterNumber())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getEquipmentRegisterNumber())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getFloorHigh())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getDoor())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getStand())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getRegistrationAuthority())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getCertificationBody())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getFactoryNumber())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getSpeed())) {
			return false;
		}
		if (elevatorDetail.getMadeDate() == null) {
			return false;
		}
		if (elevatorDetail.getElevatorUseType() == null) {
			return false;
		}
		if (elevatorDetail.getUseType() == null) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getCertNo())) {
			return false;
		}

		if (StrUtil.isEmpty(elevatorDetail.getManufactureNo())) {
			return false;
		}
		if (StrUtil.isEmpty(elevatorDetail.getHoistHeight())) {
			return false;
		}
		return true;
	}

	@Override
	public List<ElevatorDetail> listWithoutEleNum() {
		return baseMapper.listWithoutEleNum();
	}

	@Override
	public TlwScreenEleBaseInfoVO tlwScreenEleBaseInfo(String deviceId) {
		return baseMapper.tlwScreenEleBaseInfo(deviceId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateElevatorMaintainStatusDay() {

		Date recordDate = DateUtil.offsetDay(DateUtil.date(), -1);
		List<MaintainPlanConfig> planConfigs = planConfigService.listAll();
		List<ElevatorMaintainStatusDay> elevatorMaintainStatusDays = new ArrayList<>();
		planConfigs.forEach(e -> {
			ElevatorMaintainStatusDay j = new ElevatorMaintainStatusDay();
			j.setBuildingId(e.getBuildingId());
			j.setElevatorId(e.getElevatorId());
			j.setStartTime(e.getStartTime());
			j.setEndTime(e.getEndTime());
			j.setMaintainStatus(e.getMaintainStatus());
			j.setContractId(e.getContractId());
			j.setFromType(null == e.getFromType() ? -1 : e.getFromType());
			j.setFromTypeContractId(e.getFromTypeContractId());
			j.setRecordDate(recordDate);
			j.setTenantId(e.getTenantId());
			j.setAuditType(e.getAuditType());
			elevatorMaintainStatusDays.add(j);
		});
		List<List<ElevatorMaintainStatusDay>> resultList = ListUtil.partition(elevatorMaintainStatusDays, 50);
		resultList.forEach(e -> elevatorMaintainStatusDayService.saveBatch(e));

		List<Tenant> tenantList = tenantService.listAllTenant();
		List<User> maintainUserList = userService.listAllMaintainUser();
		Map<String, List<ElevatorMaintainStatusDay>> tenantElevatorGroup = elevatorMaintainStatusDays.stream().collect(Collectors.groupingBy(ElevatorMaintainStatusDay::getTenantId));
		Map<String, List<User>> tenantUserGroup = maintainUserList.stream().collect(Collectors.groupingBy(User::getTenantId));
		List<MaintainDayCount> maintainDayCounts = new ArrayList<>();
		tenantList.forEach(e -> {
			MaintainDayCount dayCount = new MaintainDayCount();
			dayCount.setTenantId(e.getTenantId());
			dayCount.setElevatorCount(0L);
			dayCount.setMaintainUserCount(0L);
			dayCount.setElevatorAuditCount(0L);
			dayCount.setElevatorNotAuditCount(0L);
			if (tenantElevatorGroup.containsKey(e.getTenantId())) {
				dayCount.setElevatorCount(tenantElevatorGroup.get(e.getTenantId()).stream().filter(j ->
					j.getFromType().equals(2) && (
						j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.CONTRACT_IN_TIME.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.CONTRACT_OUT_TIME.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.OUT_TIME_STOP.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.OUT_TIME_END.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.OUT_TIME_END_HAS_NEXT.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.DIS_ENABLE.getId()))).count());
				dayCount.setElevatorAuditCount(tenantElevatorGroup.get(e.getTenantId()).stream().filter(j ->
					j.getAuditType().equals(0) && j.getFromType().equals(2) && (
						j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.CONTRACT_IN_TIME.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.CONTRACT_OUT_TIME.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.OUT_TIME_STOP.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.OUT_TIME_END.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.OUT_TIME_END_HAS_NEXT.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.DIS_ENABLE.getId()))).count());
				dayCount.setElevatorNotAuditCount(tenantElevatorGroup.get(e.getTenantId()).stream().filter(j ->
					j.getAuditType().equals(1) && j.getFromType().equals(2) && (
						j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.CONTRACT_IN_TIME.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.CONTRACT_OUT_TIME.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.OUT_TIME_STOP.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.OUT_TIME_END.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.OUT_TIME_END_HAS_NEXT.getId())
							|| j.getMaintainStatus().equals(ElevatorMaintainStatusEnums.DIS_ENABLE.getId()))).count());
			}
			if (tenantUserGroup.containsKey(e.getTenantId())) {
				dayCount.setMaintainUserCount(tenantUserGroup.get(e.getTenantId()).stream().map(User::getId).distinct().count());
			}
			dayCount.setRecordDate(recordDate);
			maintainDayCounts.add(dayCount);
		});
		maintainDayCountService.saveBatch(maintainDayCounts);

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean initElevatorMaintainDay() {
		List<ElevatorEffected> elevatorEffecteds = elevatorEffectedService.listAll();
//		Map<String,List<ElevatorEffected>> monthGroup = elevatorEffecteds.stream().collect(Collectors.groupingBy(t -> String.format("%s~%s",DateUtil.format(DateUtil.beginOfWeek(t.getRecordDate()), "yyyy/M/d"), DateUtil.format(DateUtil.endOfWeek(t.getRecordDate()), "yyyy/M/d"))));
		Map<String, List<ElevatorEffected>> monthGroup = elevatorEffecteds.stream().collect(Collectors.groupingBy(t -> DateUtil.format(t.getRecordDate(), "yyyy-MM-dd")));
		monthGroup.forEach((k, v) -> {
			List<ElevatorMaintainStatusDay> days = new ArrayList<>();
			v.forEach(j -> {
				ElevatorMaintainStatusDay day = new ElevatorMaintainStatusDay();
				day.setElevatorId(j.getElevatorId());
				day.setBuildingId(j.getBuildingId());
				day.setContractId(j.getContractId());
				day.setMaintainStatus(ElevatorMaintainStatusEnums.CONTRACT_IN_TIME.getId());
				day.setFromType(2);
				day.setRecordDate(j.getRecordDate());
				day.setTenantId(j.getTenantId());
				days.add(day);
			});
			elevatorMaintainStatusDayService.saveBatch(days);
		});
		return Boolean.TRUE;
	}

	@Override
	public Boolean initMaintainDay() {
		List<DateTime> rangeDate = DateUtil.rangeToList(DateUtil.parse("2023-03-01"), DateUtil.yesterday(), DateField.DAY_OF_YEAR);
		List<Map<String, Object>> elevatorEffecteds = elevatorEffectedService.listAllELevatorCount();
		List<Tenant> tenantList = tenantService.listAllTenant();
		List<User> maintainUserList = userService.listAllMaintainUser();
		long userCount = maintainUserList.stream().count();
		rangeDate.forEach(t -> {
			List<MaintainDayCount> maintainDayCounts = new ArrayList<>();
			tenantList.forEach(e -> {
				MaintainDayCount dayCount = new MaintainDayCount();
				Map<String, Object> map = elevatorEffecteds.stream().filter(j -> e.getTenantId().equals(String.valueOf(j.get("tenantId"))) && String.valueOf(j.get("recordDate")).equals(DateUtil.format(t, "yyyy-MM-dd"))).findFirst().orElse(null);
				dayCount.setElevatorCount(0L);
				if (ObjectUtil.isNotEmpty(map)) {
					dayCount.setElevatorCount(Long.valueOf(String.valueOf(map.get("elevatorCount"))));
				}
				dayCount.setMaintainUserCount(userCount);
				dayCount.setRecordDate(t);
				dayCount.setTenantId(e.getTenantId());
				maintainDayCounts.add(dayCount);
			});
			maintainDayCountService.saveBatch(maintainDayCounts);
		});
		return Boolean.TRUE;
	}

	@Override
	public List<ElevatorSimpleInfoVO> selectAllElevatorSimpleInfo() {
		return baseMapper.selectAllElevatorSimpleInfo();
	}

	@Override
	public List<ElevatorDeptUserSimpleVO> selectElevatorPrincipalDeptSimpleInfo() {
		return baseMapper.selectElevatorPrincipalDeptSimpleInfo();
	}

	@Override
	public List<ElevatorVO> selectAllElevatorDetailList() {
		return baseMapper.selectAllElevatorDetailList();
	}

	@Override
	public List<Elevator> getSugarMapEleList() {
		return baseMapper.getSugarMapEleList();
	}

	/**
	 * 政府数据
	 *
	 * @return 政府数据结果
	 */
	@Override
	public List<GovernmentElevatorPoolVO> queryGovernmentElevatorPoolVOList() {
		return baseMapper.queryGovernmentElevatorPoolVOList();
	}

	@Override
	public List<GalaxyElevatorTrackUpdateDTO> getGalaxyElevatorTrackUpdateDTO() {
		return baseMapper.getGalaxyElevatorTrackUpdateDTO();
	}

	@Override
	public List<ElevatorDataReportVO> getElevatorDataReportVO() {
		return baseMapper.getElevatorDataReportVO();
	}

	@Override
	public List<GalaxyElevatorNumVO> getGalaxyElevatorNumVOs() {
		return baseMapper.getGalaxyElevatorNumVOs();
	}

	@Override
	public List<BuildingElevatorFeiShuVO> queryBuildingElevatorVOList() {
		return baseMapper.queryBuildingElevatorVOList();
	}

	@Override
	@TenantIgnore
	public List<PartPlanElevatorNumVO> getGalaxyPartsPlanElevatorNum() {
		return baseMapper.getGalaxyPartsPlanElevatorNum();
	}

	@Override
	public List<GovernmentElevatorPoolVO> queryGovernmentElevatorPoolVOFull() {
		return baseMapper.getGovernmentElevatorPoolVOFull();
	}

	@Override
	public List<ElevatorBrand> getBrandListOfElevatorId(String elevatorIds) {
		String[] split = elevatorIds.split(",");
		List<Long> ids = new ArrayList<>(16);
		for (String id : split) {
			ids.add(Convert.toLong(id));
		}
		return baseMapper.getBrandListOfElevatorId(ids);
	}


	/**
	 * 获取重复的
	 *
	 * @param list1:数据库数据
	 * @param list2       新增的数据
	 * @return
	 */
	private List<PartWordUrlVo> filterExis(List<PartWordUrlVo> list1, List<PartWordUrlVo> list2) {
		if (list1 == null || list1.size() == 0) {
			return list2;
		} else {
			list1 = JSON.parseArray(JSON.toJSONString(list1), PartWordUrlVo.class);
		}
		List<PartWordUrlVo> resultList = new ArrayList<>(16);
		List<String> urls = list1.stream().map(PartWordUrlVo::getUrl).collect(Collectors.toList());
		for (PartWordUrlVo partWordUrlVo : list2) {
			if (!urls.contains(partWordUrlVo.getUrl())) {
				resultList.add(partWordUrlVo);
			}
		}
		return resultList;
	}

	/**
	 * 电梯完整度计算
	 *
	 * @param elevator
	 * @param elevatorSaveDto
	 */
	private void elevatorIntact(ElevatorSaveDto elevatorSaveDto, Elevator elevator) {
		//非年审
		if (elevatorSaveDto.getUseType() == 1) {
			//计算类型位置
			elevator.setLwIntact(Convert.toBigDecimal(1));

			//计算维保信息
			Integer wbCounts = 2;
			Integer saveWbCounts = 0;
			if (StrUtil.isNotEmpty(elevatorSaveDto.getWbPhone())) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (elevatorSaveDto.getWbPhoneImg() != null && elevatorSaveDto.getWbPhoneImg().size() > 0) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (saveWbCounts > 0) {
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveWbCounts).divide(Convert.toBigDecimal(wbCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setWbIntact(bigDecimal2);
			} else {
				elevator.setWbIntact(Convert.toBigDecimal(0));
			}
			//计算设备技术完整性
			elevator.setSbJsIntact(Convert.toBigDecimal(1));

			ElevatorFieldV fieldV = elevatorSaveDto.getFieldV();
			Long driveModeId = Convert.toLong(fieldV.getDriveModeId(), 0L);
			if (driveModeId.equals(1441306947313549315L) || driveModeId.equals(1441306947313549317L) || driveModeId.equals(1441306947313549328L) || driveModeId.equals(1441306947313549320L) || driveModeId.equals(1441306947313549322L) || driveModeId.equals(1441306947162554369L)) {
				//计算维保信息
				Integer sbJsCounts = 9;
				Integer saveSbJsCounts = 6;
				if (elevatorSaveDto.getFloorTier() != null && elevatorSaveDto.getFloorTier().size() > 0 && elevatorSaveDto.getFloorTier().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorPlatforms() != null && elevatorSaveDto.getFloorPlatforms().size() > 0 && elevatorSaveDto.getFloorPlatforms().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorDoors() != null && elevatorSaveDto.getFloorDoors().size() > 0 && elevatorSaveDto.getFloorDoors().stream().filter(o -> o.getIsBackDoor() == true || o.getIsFrontDoor() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveSbJsCounts).divide(Convert.toBigDecimal(sbJsCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbJsIntact(bigDecimal2);
			} else if (driveModeId.equals(1441306947313549333L) || driveModeId.equals(1441306947313549326L) || driveModeId.equals(1441306947313549336L)) {
				Integer sbJsCounts = 12;
				Integer saveSbJsCounts = 9;
				if (elevatorSaveDto.getFloorTier() != null && elevatorSaveDto.getFloorTier().size() > 0 && elevatorSaveDto.getFloorTier().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorPlatforms() != null && elevatorSaveDto.getFloorPlatforms().size() > 0 && elevatorSaveDto.getFloorPlatforms().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorDoors() != null && elevatorSaveDto.getFloorDoors().size() > 0 && elevatorSaveDto.getFloorDoors().stream().filter(o -> o.getIsBackDoor() == true || o.getIsFrontDoor() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveSbJsCounts).divide(Convert.toBigDecimal(sbJsCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbJsIntact(bigDecimal2);
			}
			//保险完整度
			// 2024-10-31 应远哥要求，非年审保险和zc完整度设置1
			elevator.setBxIntact(Convert.toBigDecimal(1));
			elevator.setSbZcIntact(Convert.toBigDecimal(1));
			//出厂
			elevator.setCcIntact(Convert.toBigDecimal(1));

			//使用信息
			if (elevatorSaveDto.getSecurityGuardName() == null) {
				elevator.setSyIntact(Convert.toBigDecimal(0));
			} else {
				elevator.setSyIntact(Convert.toBigDecimal(1));
			}

			//安装信息
			if (elevatorSaveDto.getAzCheckBeginDate() != null) {
				elevator.setAzIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setAzIntact(Convert.toBigDecimal(0));
			}

			//梯无忧
			if (elevatorSaveDto.getElevatorNumImg() != null && elevatorSaveDto.getElevatorNumImg().size() > 0) {
				elevator.setTwyIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setTwyIntact(Convert.toBigDecimal(0));
			}

			//电梯结构
			ElevatorPartsStructureTemplateRelation detail = elevatorPartsStructureTemplateRelationService.getOne(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery().eq(ElevatorPartsStructureTemplateRelation::getElevatorId, elevator.getId()), false);
			if (detail != null && detail.getStructureTemplateId() != null) {
				elevator.setJgIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setJgIntact(Convert.toBigDecimal(0));
			}
		} else {
			//计算类型位置
			elevator.setLwIntact(Convert.toBigDecimal(1));

			//计算维保信息
			Integer wbCounts = 3;
			Integer saveWbCounts = 0;
			if (StrUtil.isNotEmpty(elevatorSaveDto.getWbPhone())) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (elevatorSaveDto.getWbPhoneImg() != null && elevatorSaveDto.getWbPhoneImg().size() > 0) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (elevatorSaveDto.getWbExtUrl() != null && elevatorSaveDto.getWbExtUrl().size() > 0) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (saveWbCounts > 0) {
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveWbCounts).divide(Convert.toBigDecimal(wbCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setWbIntact(bigDecimal2);
			} else {
				elevator.setWbIntact(Convert.toBigDecimal(0));
			}


			//计算设备技术完整性
			elevator.setSbJsIntact(Convert.toBigDecimal(1));
			Long driveModeId = elevatorSaveDto.getElevatorUseType();

			if (driveModeId.equals(1441306947313549315L) || driveModeId.equals(1441306947313549317L) || driveModeId.equals(1441306947313549328L) || driveModeId.equals(1441306947313549320L) || driveModeId.equals(1441306947313549322L) || driveModeId.equals(1441306947162554369L)) {
				//计算维保信息
				Integer sbJsCounts = 9;
				Integer saveSbJsCounts = 6;
				if (elevatorSaveDto.getFloorTier() != null && elevatorSaveDto.getFloorTier().size() > 0 && elevatorSaveDto.getFloorTier().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorPlatforms() != null && elevatorSaveDto.getFloorPlatforms().size() > 0 && elevatorSaveDto.getFloorPlatforms().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorDoors() != null && elevatorSaveDto.getFloorDoors().size() > 0 && elevatorSaveDto.getFloorDoors().stream().filter(o -> o.getIsBackDoor() == true || o.getIsFrontDoor() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveSbJsCounts).divide(Convert.toBigDecimal(sbJsCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbJsIntact(bigDecimal2);
			} else if (driveModeId.equals(1441306947313549333L) || driveModeId.equals(1441306947313549326L) || driveModeId.equals(1441306947313549336L)) {
				Integer sbJsCounts = 12;
				Integer saveSbJsCounts = 9;
				if (elevatorSaveDto.getFloorTier() != null && elevatorSaveDto.getFloorTier().size() > 0 && elevatorSaveDto.getFloorTier().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorPlatforms() != null && elevatorSaveDto.getFloorPlatforms().size() > 0 && elevatorSaveDto.getFloorPlatforms().stream().filter(o -> o.getIsHas() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				if (elevatorSaveDto.getFloorDoors() != null && elevatorSaveDto.getFloorDoors().size() > 0 && elevatorSaveDto.getFloorDoors().stream().filter(o -> o.getIsBackDoor() == true || o.getIsFrontDoor() == true).collect(Collectors.toList()).size() > 0) {
					saveSbJsCounts = saveSbJsCounts + 1;
				}
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveSbJsCounts).divide(Convert.toBigDecimal(sbJsCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbJsIntact(bigDecimal2);
			}

			//计算保险信息
			Integer bxCounts = 3;
			Integer saveBxCounts = 0;
			if (elevatorSaveDto.getBxCompanyId() != null) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevatorSaveDto.getBxCompanyEndDate() != null) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevatorSaveDto.getBxExtUrl() != null && elevatorSaveDto.getBxExtUrl().size() > 0) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (saveBxCounts > 0) {
				BigDecimal bigDecimal = Convert.toBigDecimal(saveBxCounts).divide(Convert.toBigDecimal(bxCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setBxIntact(bigDecimal);
			} else {
				elevator.setBxIntact(Convert.toBigDecimal(0));
			}

			//设备注册信息
			Integer sbZcCounts = 4;
			Integer saveSbZcCounts = 0;
			if (StrUtil.isNotEmpty(elevatorSaveDto.getPrivateNum())) {
				saveSbZcCounts = saveSbZcCounts + 1;
			}
			if (StrUtil.isNotEmpty(elevatorSaveDto.getEquipmentRegisterNumber())) {
				saveSbZcCounts = saveSbZcCounts + 1;
			}
			if (StrUtil.isNotEmpty(elevatorSaveDto.getRegisterNumber())) {
				saveSbZcCounts = saveSbZcCounts + 1;
			}
			if (elevatorSaveDto.getCertificateMarkList() != null && elevatorSaveDto.getCertificateMarkList().size() > 0) {
				List<ElevatorAttachmentHistory> list = elevatorSaveDto.getCertificateMarkList().stream().filter(o -> o.getStatus() == ElevatorAttachmentEnum.IMG.getStatus()).collect(Collectors.toList());
				if (list.size() > 0) {
					saveSbZcCounts = saveSbZcCounts + 1;
				}
			}
			if (saveSbZcCounts > 0) {
				BigDecimal bigDecimal3 = Convert.toBigDecimal(saveSbZcCounts).divide(Convert.toBigDecimal(sbZcCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbZcIntact(bigDecimal3);
			} else {
				elevator.setSbZcIntact(Convert.toBigDecimal(0));
			}

			//出厂
			elevator.setCcIntact(Convert.toBigDecimal(1));

			if (StrUtil.isNotEmpty(elevatorSaveDto.getSecurityGuardName())) {
				elevator.setSyIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setSyIntact(Convert.toBigDecimal(0));
			}

			//安装信息
			if (elevatorSaveDto.getAzCheckBeginDate() != null) {
				elevator.setAzIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setAzIntact(Convert.toBigDecimal(0));
			}

			//梯无忧
			if (elevatorSaveDto.getElevatorNumImg() != null && elevatorSaveDto.getElevatorNumImg().size() > 0) {
				elevator.setTwyIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setTwyIntact(Convert.toBigDecimal(0));
			}

			//电梯结构
			ElevatorPartsStructureTemplateRelation detail = elevatorPartsStructureTemplateRelationService.getOne(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery().eq(ElevatorPartsStructureTemplateRelation::getElevatorId, elevator.getId()), false);
			if (detail != null && detail.getStructureTemplateId() != null) {
				elevator.setJgIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setJgIntact(Convert.toBigDecimal(0));
			}
		}

	}


	@Override
	public void elevatorInit(Elevator elevator) {


		ElevatorDetail elevatorDetail1 = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId, elevator.getId()));
		ElevatorFieldV elevatorFieldV = elevatorFieldVService.getOne(Wrappers.<ElevatorFieldV>lambdaQuery().eq(ElevatorFieldV::getElevatorId, elevator.getId()));

		List<ElevatorAttachmentHistory> attachmentHistories = elevatorAttachmentHistoryService.list();
		Map<Long, List<ElevatorAttachmentHistory>> attachmentHistoryMap = attachmentHistories.stream().collect(Collectors.groupingBy(ElevatorAttachmentHistory::getElevatorId));
		//年审
		if (elevatorDetail1.getUseType() == 0) {
			//计算维保信息
			Integer wbCounts = 3;
			Integer saveWbCounts = 0;
			if (StrUtil.isNotEmpty(elevator.getWbPhone())) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (elevator.getWbPhoneImg() != null && elevator.getWbPhoneImg().size() > 0) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (elevator.getWbExtUrl() != null && elevator.getWbExtUrl().size() > 0) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (saveWbCounts > 0) {
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveWbCounts).divide(Convert.toBigDecimal(wbCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setWbIntact(bigDecimal2);
			}

			//计算保险信息
			elevator.setBxIntact(Convert.toBigDecimal(0));
			Integer bxCounts = 3;
			Integer saveBxCounts = 0;
			if (elevator.getBxCompanyId() != null) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevator.getBxCompanyEndDate() != null) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevator.getBxExtUrl() != null && elevator.getBxExtUrl().size() > 0) {
				saveBxCounts = saveBxCounts + 1;
			}
			BigDecimal bigDecimal2 = Convert.toBigDecimal(saveBxCounts).divide(Convert.toBigDecimal(bxCounts), 2, BigDecimal.ROUND_HALF_UP);
			elevator.setBxIntact(bigDecimal2);

			//设备注册信息
			Integer sbZcCounts = 4;
			Integer saveSbZcCounts = 0;
			if (StrUtil.isNotEmpty(elevator.getPrivateNum())) {
				saveSbZcCounts = saveSbZcCounts + 1;
			}
			if (elevatorDetail1 != null) {
				if (StrUtil.isNotEmpty(elevatorDetail1.getEquipmentRegisterNumber())) {
					saveSbZcCounts = saveSbZcCounts + 1;
				}
				if (StrUtil.isNotEmpty(elevatorDetail1.getRegisterNumber())) {
					saveSbZcCounts = saveSbZcCounts + 1;
				}
			}
			if (attachmentHistoryMap.get(elevator.getId()) != null && attachmentHistoryMap.get(elevator.getId()).size() > 0) {
				List<ElevatorAttachmentHistory> list2 = attachmentHistoryMap.get(elevator.getId()).stream().filter(o -> o.getStatus() == ElevatorAttachmentEnum.IMG.getStatus()).collect(Collectors.toList());
				if (list2.size() > 0) {
					saveSbZcCounts = saveSbZcCounts + 1;
				}
			}
			if (saveSbZcCounts > 0) {
				BigDecimal bigDecimal3 = Convert.toBigDecimal(saveSbZcCounts).divide(Convert.toBigDecimal(sbZcCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setSbZcIntact(bigDecimal3);
			} else {
				elevator.setSbZcIntact(Convert.toBigDecimal(0));
			}


			//梯无忧
			if (elevatorDetail1.getElevatorNumImg() != null && elevatorDetail1.getElevatorNumImg().size() > 0) {
				elevator.setTwyIntact(Convert.toBigDecimal(1));
			} else {
				elevator.setTwyIntact(Convert.toBigDecimal(0));
			}


		} else if (elevatorDetail1.getUseType() == 1) {
			//计算维保信息
			Integer wbCounts = 2;
			Integer saveWbCounts = 0;
			if (StrUtil.isNotEmpty(elevator.getWbPhone())) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (elevator.getWbPhoneImg() != null && elevator.getWbPhoneImg().size() > 0) {
				saveWbCounts = saveWbCounts + 1;
			}
			if (saveWbCounts > 0) {
				BigDecimal bigDecimal2 = Convert.toBigDecimal(saveWbCounts).divide(Convert.toBigDecimal(wbCounts), 2, BigDecimal.ROUND_HALF_UP);
				elevator.setWbIntact(bigDecimal2);
			} else {
				elevator.setWbIntact(Convert.toBigDecimal(0));
			}

			//计算保险信息
			elevator.setBxIntact(Convert.toBigDecimal(0));
			Integer bxCounts = 3;
			Integer saveBxCounts = 0;
			if (elevator.getBxCompanyId() != null) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevator.getBxCompanyEndDate() != null) {
				saveBxCounts = saveBxCounts + 1;
			}
			if (elevator.getBxExtUrl() != null && elevator.getBxExtUrl().size() > 0) {
				saveBxCounts = saveBxCounts + 1;
			}
			BigDecimal bigDecimal2 = Convert.toBigDecimal(saveBxCounts).divide(Convert.toBigDecimal(bxCounts), 2, BigDecimal.ROUND_HALF_UP);
			elevator.setBxIntact(bigDecimal2);
			//梯无忧
			if (elevatorDetail1 != null) {
				if (elevatorDetail1.getElevatorNumImg() != null && elevatorDetail1.getElevatorNumImg().size() > 0) {
					elevator.setTwyIntact(Convert.toBigDecimal(1));
				} else {
					elevator.setTwyIntact(Convert.toBigDecimal(0));
				}
			}
		}
		this.updateById(elevator);
	}

	@Override
	public IPage<ElevatorIntactVo> pageList(ElevatorIntactSearchVo elevatorIntactSearchVo) {
		Query query = new Query();
		query.setSize(elevatorIntactSearchVo.getSize());
		query.setCurrent(elevatorIntactSearchVo.getCurrent());
		IPage<ElevatorIntactVo> page = Condition.getPage(query);
		if (elevatorIntactSearchVo.getSize() == 0) {
			List<ElevatorIntactVo> list = baseMapper.pageList(null, elevatorIntactSearchVo);
			page.setRecords(list);
		} else {
			List<ElevatorIntactVo> list = baseMapper.pageList(page, elevatorIntactSearchVo);
			page.setRecords(list);
		}
		return page;
	}

	@Override
	public String getModeNameByElevatorId(Long elevatorId) {
		return baseMapper.getModeNameByElevatorId(elevatorId);

	}

	@Override
	public List<ElevatorSearchConditionVO> getElevatorByPrivateNum(String privateNum) {
		return baseMapper.getElevatorByPrivateNum(privateNum);
	}

	@Override
	public List<ElevatorSearchConditionVO> getElevatorByRegisterNumber(String registerNumber) {
		return baseMapper.getElevatorByRegisterNumber(registerNumber);
	}

	@Override
	public List<ElevatorSearchConditionVO> getElevatorByEquipmentRegisterNumber(String equipmentRegisterNumber) {
		return baseMapper.getElevatorByEquipmentRegisterNumber(equipmentRegisterNumber);
	}

	@Override
	public List<SidaElevatorBasicVO> getElevatorListByTenantId(String tenantId) {
		return baseMapper.getElevatorListByTenantId(tenantId);
	}

	/**
	 * 比较电梯层站
	 */
	private boolean floorPlatformsCompare(List<ElevatorFloorVo> oldFloorPlatforms, List<ElevatorFloorVo> floorPlatforms) {
		if (oldFloorPlatforms == null) {
			return Boolean.FALSE;
		}
		List<ElevatorFloorVo> oldFloorList = JSON.parseArray(JSON.toJSONString(oldFloorPlatforms), ElevatorFloorVo.class);
		String oldFloorPlatformsStr = oldFloorList.stream().filter(ElevatorFloorVo::getIsHas).sorted(Comparator.comparing(ElevatorFloorVo::getFloorNum)).map(ElevatorFloorVo::getFloorNum).collect(Collectors.joining("/"));
		String floorPlatformsStr = floorPlatforms.stream().filter(ElevatorFloorVo::getIsHas).sorted(Comparator.comparing(ElevatorFloorVo::getFloorNum)).map(ElevatorFloorVo::getFloorNum).collect(Collectors.joining("/"));
		return Func.equalsSafe(oldFloorPlatformsStr, floorPlatformsStr);
	}

	/**
	 * 比较电梯层门
	 */
	private boolean floorDoorsCompare(List<ElevatorFloorVo> oldFloorDoors, List<ElevatorFloorVo> floorDoors) {
		if (oldFloorDoors == null) {
			return Boolean.FALSE;
		}
		List<ElevatorFloorVo> oldDoorsList = JSON.parseArray(JSON.toJSONString(oldFloorDoors), ElevatorFloorVo.class);
		String oldFloorDoorsStr = oldDoorsList.stream().sorted(Comparator.comparing(ElevatorFloorVo::getFloorNum)).map(o -> String.format("%s_%s_%s", o.getFloorNum(), o.getIsBackDoor(), o.getIsFrontDoor())).collect(Collectors.joining("/"));
		String floorDoorsStr = floorDoors.stream().sorted(Comparator.comparing(ElevatorFloorVo::getFloorNum)).map(o -> String.format("%s_%s_%s", o.getFloorNum(), o.getIsBackDoor(), o.getIsFrontDoor())).collect(Collectors.joining("/"));
		return Func.equalsSafe(oldFloorDoorsStr, floorDoorsStr);
	}

	@Override
	public List<GovernmentElevatorPoolVO> getUnMarkList(List<String> markedDeviceCodeList) {
		return baseMapper.getUnMarkList(markedDeviceCodeList);
	}

	@Override
	public List<GovernmentElevatorPoolVO> getUnMarkListFull() {
		return baseMapper.getUnMarkListFull();
	}

	@Override
	public List<BIScreenElevatorVO> selectBIScreenBuildingElevator(String startDate, String endDate) {
		return baseMapper.selectBIScreenBuildingElevator(startDate, endDate);
	}

	@Override
	public List<BIScreenElevatorPlanVO> selectBIScreenBuildingElevatorWx(String startDate, String endDate) {
		return baseMapper.selectBIScreenBuildingElevatorWx(startDate, endDate);
	}

	@Override
	public List<BIScreenElevatorPlanPartsVO> selectBuildingElevatorWxWork(String startDate, String endDate) {
		return baseMapper.selectBuildingElevatorWxWork(startDate, endDate);
	}

	@Override
	public List<BIScreenElevatorPlanPartsVO> selectBuildingElevatorPartsWork(String startDate, String endDate) {
		return baseMapper.selectBuildingElevatorPartsWork(startDate, endDate);
	}

	@Override
	public List<ElevatorMaintainCostListDTO> selectElevatorMaintainCostList(List<Long> elevatorIds) {
		return baseMapper.selectElevatorMaintainCostList(elevatorIds);
	}

	@Override
	@TenantIgnore
	public int getMonitorElevatorCount(Date rangeEndDate) {
		return baseMapper.getMonitorElevatorCount(rangeEndDate);
	}

	@Override
	public List<String> getElevatorPhones() {
		String tenantId = AuthUtil.getTenantId();
		TenantExt tenantExt = tenantExtService.getOne(Wrappers.<TenantExt>lambdaQuery().eq(TenantExt::getTenantId, tenantId));
		List<String> list = new ArrayList<>(10);
		if (tenantExt != null && tenantExt.getPhoneAllDay() != null && tenantExt.getPhoneAllDay().size() > 0) {
			List<RescuePhoneVo> phoneAllDay = JSON.parseArray(JSON.toJSONString(tenantExt.getPhoneAllDay()), RescuePhoneVo.class);
			for (RescuePhoneVo rescuePhoneVo : phoneAllDay) {
				if (StrUtil.isNotEmpty(rescuePhoneVo.getPhone())) {
					list.add(Convert.toStr(rescuePhoneVo.getPhone()));
				}
			}
		}
		return list;
	}

	@Override
	public void downExcelElevatorPrincipal_v2(ElevatorPrincipalQueryDTO queryDTO, List<List<String>> rows) {
		// 处理获取部门子集
		if (ObjectUtil.isNotEmpty(queryDTO.getDeptIds())) {
			List<Long> deptIdList = new ArrayList<>();
			queryDTO.getDeptIds().forEach(e -> {
				List<Dept> childIds = deptService.getDeptChild(e);
				if (ObjectUtil.isNotEmpty(childIds)) {
					deptIdList.addAll(childIds.stream().map(Dept::getId).collect(Collectors.toList()));
				}
			});
			deptIdList.addAll(queryDTO.getDeptIds());
			queryDTO.setDeptIds(deptIdList);
		}
		// 设置维保负责人
		queryDTO.setType(1);
		List<ElevatorPrincipalPageVO> pageVOS = baseMapper.selectElevatorPrincipal(queryDTO);
		List<ContractElevatorVoV2> buildingContractPluses = baseMapper.downContractPlusExcel();
		final Map<Long, List<ContractElevatorVoV2>> listMap = buildingContractPluses.stream().collect(Collectors.groupingBy(ContractElevatorVoV2::getElevatorId));
		if (ObjectUtil.isNotEmpty(pageVOS)) {
			pageVOS.forEach(e -> {
				List<String> row = new ArrayList<>(11);
				row.add(Convert.toStr(e.getBuildingName()));
				row.add(Convert.toStr(e.getBuildingAddress()));
				row.add(Convert.toStr(e.getElevatorAddress()));
				row.add(Convert.toStr(ElevatorAuditTypeEnum.getName(e.getUseType())));
				if (Convert.toInt(e.getMaintainStatus(), -1).equals(ElevatorMaintainStatusEnums.RELEASE_INSURANCE.getId())) {
					row.add("暂停维保");
				} else {
					row.add("维保电梯");
				}
				row.add(Convert.toStr(e.getMaintainStatusName(), "--"));
				row.add(Convert.toStr(e.getEleMaintainStatusDesc()));
				if (e.getUseType().equals(ElevatorAuditTypeEnum.AUDIT.getStatus())) {
					if (ObjectUtil.isNotEmpty(e.getOverdueDate())) {
						Date now = DateUtil.parseDate(DateUtil.today());
						if (e.getOverdueDate().getTime() == now.getTime()) {
							row.add("明天即将违规");
							row.add("");
						} else if (e.getOverdueDate().getTime() > now.getTime()) {
							row.add("正常");
							row.add("");
						} else {
							long betweenDay = DateUtil.between(e.getOverdueDate(), now, DateUnit.DAY);
							row.add("已违规");
							row.add(Convert.toStr(betweenDay));
						}
					} else {
						row.add("");
						row.add("");
					}
				} else {
					row.add("");
					row.add("");
				}
				row.add(Convert.toStr(DateUtil.format(e.getPreviousPlanDate(), "yyyy-MM-dd")));
				row.add(Convert.toStr(DateUtil.format(e.getNextPlanDate(), "yyyy-MM-dd")));
				row.add(Convert.toStr(StringUtil.isNotBlank(e.getPrincipalDeptName()) ? e.getPrincipalDeptName() : "未分配"));
				row.add(Convert.toStr(StringUtil.isNotBlank(e.getPrincipalUserNames()) ? e.getPrincipalUserNames() : "未分配"));
				row.add(Convert.toStr(DateUtil.format(e.getUpdateTime(), "yyyy-MM-dd HH:mm:ss")));
				Integer toInt = Convert.toInt(e.getFromType(), 0);
				if (toInt == 1) {
					row.add("外包合同");
				} else if (toInt == 2) {
					row.add("非外包合同");
				} else {
					row.add("/");
				}
				row.add(Convert.toStr(e.getElevatorNum()));
				row.add(Convert.toStr(getTypeName(e.getBuildingType())));
				row.add(Convert.toStr(e.getBrandName()));
				row.add(Convert.toStr(e.getPrivateNum()));

				List<ContractElevatorVoV2> contractElevatorVoV2s = listMap.get(e.getElevatorId());
				if (contractElevatorVoV2s == null || contractElevatorVoV2s.size() == 0) {
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
					row.add("/");
				} else {
					ContractElevatorVoV2 contractElevatorVoV2 = contractElevatorVoV2s.get(0);
					row.add(Convert.toStr(contractElevatorVoV2.getContractNo(), "/"));
					row.add(Convert.toStr(getCheckName(contractElevatorVoV2.getStatus()), "/"));
					row.add(Convert.toStr(getContractSourceName(contractElevatorVoV2.getContractSource()), "-1"));
					row.add(Convert.toStr(getContractTypeName(contractElevatorVoV2.getContractType()), "-1"));
					row.add(contractElevatorVoV2.getIsQuaGuarantee() == 1 ? "是" : "否");
					row.add(Convert.toStr(contractElevatorVoV2.getCustomerUnitName(), "/"));
					row.add(Convert.toStr(contractElevatorVoV2.getCustomerUnit(), "/"));
					row.add(Convert.toStr(contractElevatorVoV2.getCustomerPhone(), "/"));
					row.add(contractElevatorVoV2.getFromType() == 1 ? "是" : "否");
					row.add(Convert.toStr(contractElevatorVoV2.getMaintainUnit(), "/"));
					row.add(Convert.toStr(contractElevatorVoV2.getMaintainMainUserName(), "/"));
					row.add(DateUtil.format(contractElevatorVoV2.getContractBeginTime(), "yyyy-MM-dd HH:mm:ss"));
					row.add(DateUtil.format(contractElevatorVoV2.getContractEndTime(), "yyyy-MM-dd HH:mm:ss"));
					row.add(Convert.toInt(contractElevatorVoV2.getIsLive(), -1) == 2 ? "是" : "否");
					row.add(Convert.toStr(contractElevatorVoV2.getYearCostDesc(), "/"));
					row.add(Convert.toStr(contractElevatorVoV2.getYearSpeedGovernorCost(), "/"));
					row.add(Convert.toStr(contractElevatorVoV2.getMonthCostDesc(), "/"));
					row.add(Convert.toStr(contractElevatorVoV2.getMaintainCounts(), "0"));
					row.add(Convert.toStr(getPayDateTypeName(contractElevatorVoV2.getPayDateType()), "/"));
					row.add(Convert.toStr(contractElevatorVoV2.getContractCost(), "0"));
					row.add(Convert.toStr(getpayDateDescName(contractElevatorVoV2.getPayDateDesc()), "0"));
					row.add(Convert.toStr(getPayTypeName(contractElevatorVoV2.getPayType()), "0"));
				}
				rows.add(row);
			});
		}
	}

	@Override
	public List<SimpleElevatorInfoVO> listSimpleElevatorInfoByIds(List<Long> elevatorIds) {
		return baseMapper.listSimpleElevatorInfoByIds(elevatorIds);
	}


	/**
	 * 获取审核状态
	 * 状态1:未审核，2:审核通过，3审核未通过
	 *
	 * @param status
	 * @return
	 */
	private String getCheckName(Integer status) {
		status = Convert.toInt(status, -1);
		if (status == 1) {
			return "未审核";
		}
		if (status == 2) {
			return "审核通过";
		}
		if (status == 3) {
			return "审核未通过";
		}
		return "-";
	}

	/**
	 * 合同来源	1:新签	2:续签	3:转签	4:丢失	5:夺回	6:新梯移交	7:免保转签
	 */
	private String getContractSourceName(Integer status) {
		status = Convert.toInt(status, -1);
		if (status == 1) {
			return "新签";
		} else if (status == 2) {
			return "续签";
		} else if (status == 3) {
			return "转签";
		} else if (status == 4) {
			return "丢失";
		} else if (status == 5) {
			return "夺回";
		} else if (status == 6) {
			return "新梯移交";
		} else if (status == 7) {
			return "免保转签";
		} else {
			return "-";
		}
	}


	/**
	 * 庸与字段(用于列表刷选)	合同类型	1:保养合同	2:委托合同	3:质保合同	4:维系合同
	 */

	private String getContractTypeName(Integer status) {
		status = Convert.toInt(status, -1);
		if (status == 1) {
			return "保养合同";
		} else if (status == 2) {
			return "委托合同";
		} else if (status == 3) {
			return "质保合同";
		} else if (status == 4) {
			return "维修合同";
		} else {
			return "-";
		}
	}


	/**
	 * 付款周期	1:周期结束时付款	2:周期中期时付款	3:周期开始时付款
	 */
	private String getPayDateTypeName(Integer status) {
		status = Convert.toInt(status, -1);
		if (status == 1) {
			return "周期结束时付款";
		} else if (status == 2) {
			return "周期中期时付款";
		} else if (status == 3) {
			return "周期开始时付款";
		} else {
			return "-";
		}
	}

	/**
	 * 支付方式	1:月结	2:两月结	3:季度结	4:四月结	5:半年结	6:年度结	7:预付50%	8:完结50%	9:一次性付款	10:免费
	 */
	private String getpayDateDescName(Integer status) {
		status = Convert.toInt(status, -1);
		if (status == 1) {
			return "月结";
		} else if (status == 2) {
			return "两月结";
		} else if (status == 3) {
			return "季度结";
		} else if (status == 4) {
			return "四月结";
		} else if (status == 5) {
			return "半年结";
		} else if (status == 6) {
			return "年度结";
		} else if (status == 7) {
			return "预付50%";
		} else if (status == 8) {
			return "完结50%";
		} else if (status == 9) {
			return "一次性付款";
		} else if (status == 10) {
			return "免费";
		} else {
			return "-";
		}
	}

	/**
	 * 1:支票	2:现金	3:电汇	4:成若电汇
	 *
	 * @param status
	 * @return
	 */
	private String getPayTypeName(Integer status) {
		status = Convert.toInt(status, -1);
		if (status == 1) {
			return "支票";
		} else if (status == 2) {
			return "现金";
		} else if (status == 3) {
			return "电汇";
		} else if (status == 4) {
			return "承兑电汇";
		} else {
			return "-";
		}
	}

	public String getTypeName(Integer type) {
		Map<String, String> elementMap = new HashMap<>(16);
		if (!Func.isNull(type)) {
			if (type == 1) {
				elementMap.put("项目类型", "小区");
			} else if (type == 2) {
				elementMap.put("项目类型", "别墅");
			} else if (type == 3) {
				elementMap.put("项目类型", "商超");
			} else if (type == 4) {
				elementMap.put("项目类型", "酒店/民宿");
			} else if (type == 5) {
				elementMap.put("项目类型", "学校");
			} else if (type == 6) {
				elementMap.put("项目类型", "医院");
			} else if (type == 7) {
				elementMap.put("项目类型", "工厂");
			} else if (type == 8) {
				elementMap.put("项目类型", "其他");
			} else if (type == 9) {
				elementMap.put("项目类型", "办公楼");
			} else if (type == 10) {
				elementMap.put("项目类型", "政府单位");
			} else if (type == 11) {
				elementMap.put("项目类型", "公共设施");
			} else if (type == 12) {
				elementMap.put("项目类型", "出租房");
			}
		}
		return Convert.toStr(elementMap.get("项目类型"));
	}

}




